package com.wits.platform.service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.dao.BaseDao;
import com.wits.platform.web.mvc.PageParam;

/**
 * 
 *  
 * 注意
 * 
 * @param <T>
 * @param <ID>
 */
public abstract class BaseService<T,ID extends Serializable> {

	protected BaseDao<T,ID> baseDao;
	
	
	//protected abstract void setBaseDao(BaseDao<T, ID> baseDao);


	public  T save(T entity){
		return baseDao.save(entity);
	}
	
	public T getOne(ID id){
		return baseDao.findOne(id);
	}
	
	public List<T> findAll(){
		return (List<T>)baseDao.findAll();
	}
	
	
	public List<T> findAll(List<ID> idList){
		return (List<T>)baseDao.findAll(idList);
	}
	
	public Page<T> findPage(Class<T> entityClass,Map<String, Object> filterParams,PageParam page){
		PageRequest pageRequest = PageUtil.buildPageRequest(page);
		Specification<T> spec = PageUtil.buildSpecification(entityClass,filterParams);
		return baseDao.findAll(spec, pageRequest);
	}
	
	public void delete(ID id) {
		baseDao.delete(id);
	}
	
	public void delete(T entity){
		baseDao.delete(entity);
	}
	
	/**
	 * 有关联关系调用api方法自动解除关系
	 * @param idList
	 */
	public void deleteInBatch(List<ID> idList){
		for(ID id : idList){
			this.delete(id);
		}
	}
	
	
	/**
	 * 
	 * 利用反射更新(低效率)
	 * @param entityClass
	 * @param Id 实体主键
	 * @param fieldName 属性名称
	 * @param fieldValue 属性值
	 * @throws Exception
	 */
	public void updateField(Class<T> entityClass, Serializable Id,String fieldName, Object fieldValue) throws Exception{
		baseDao.updateField(entityClass, Id, fieldName, fieldValue);
	}
	
	/**
	 * 
	 * 利用反射更新(低效率)
	 * @param entityClass
	 * @param Id 实体主键
	 * @param map(key:属性名,value:属性值)
	 * @throws Exception
	 */
	public void updateField(Class<T> entityClass, Serializable Id, Map<String,Object> map) throws Exception{
		baseDao.updateField(entityClass, Id, map);
	}



	
}
